<?php
/******************************************************************************
 *
 *    OpenZoowa - Web App to manage events
 *    Copyright (C) 2008 Jesus Ruiz-Ayucar
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/
   class Tag {
      public $tags;
      public $event_id;
      public $date;

      public function Tag($event_id = null) {
         if (isset($event_id) && !empty($event_id)) {
            global $db;

            $SQL = 'SELECT * FROM '.$GLOBALS["db_pre"].'tags ';
            $SQL .= 'WHERE event_id = ' . $db->escape($event_id);
            $res = $db->get_results($SQL);
            $tags = array();

            $total = count($res);
            for($i = 0; $i < $total; $i++) {
               $tags[$i] = $res[$i]->tag;
               $this->date = $res[$i]->date_tag;
            }
            $this->tags = implode(', ', $tags);
            $this->event_id = $db->escape($event_id);
         } else {
            $tags = "";
            $event_id = null;
            $date = "";
         }
      }

      public function save() {
         global $db;

         // Borramos los tags anteriores
         $SQL = 'DELETE FROM '.$GLOBALS["db_pre"].'tags WHERE ';
         $SQL .= 'event_id = ' . $this->event_id;
         $db->query($SQL);

         // Insertamos los nuevos
         $tag_list = explode(',', $this->tags);
         foreach($tag_list as $tag) {
            if($tag != "") {
               $SQL  = 'INSERT INTO '.$GLOBALS["db_pre"].'tags(tag, event_id) ';
               $SQL .= 'VALUES (';
               $SQL .= '"' . trim($tag) . '", ';
               $SQL .= $this->event_id;
               $SQL .= ')';
               $db->query($SQL);
            }
         }
      }

      public function setEventId($id) {
         $this->event_id = $id;
      }

      public function __toString() {
         return $this->tags;
      }
   }
?>